package com.google.code.bankagregator.adapter.bank.alpha.parser.credit;

import com.google.code.bankagregator.adapter.bank.alpha.parser.FuncForDepParsers;
import com.google.code.bankagregator.adapter.exception.AdapterConnectException;
import com.google.code.bankagregator.entities.*;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: kirill
 * Date: 01.06.13
 * Time: 1:48
 * To change this template use File | Settings | File Templates.
 */
public class AlphaConsCreditParser {

    private String CREDIT_URL = "http://www.alfabank.com.ua/retail/credits/alfaexpress";


    private Credit credit;
    public Bank bank = null;

    public AlphaConsCreditParser() throws AdapterConnectException {
        bank = new Bank();
        bank.setName("ПАО «Альфа-Банк» Украина");
        bank.setUrl("http://www.alfabank.com.ua/");
        credit = new Credit();
    }

    /**
     * Get credit`s params for the consumer credit
     *
     * @return credit`s params
     * @throws AdapterConnectException
     */
    public List<Credit> getCredit() throws AdapterConnectException {
        List<Credit> creditParam = new ArrayList<>();
        Pattern p = Pattern.compile("(%|от|до|минут|мес)");
        Matcher matcher = null;
        Document con = new FuncForDepParsers(CREDIT_URL).con;
        Elements params = con.select("div.list table tbody tr td ul li strong");
        List<String> intermediate = new ArrayList<>();
        for (int i = 1; i < params.size(); i++) {
            matcher = p.matcher(params.get(i).text());
            intermediate.add(matcher.replaceAll("").trim());
        }

        int term = Integer.parseInt(intermediate.get(1).substring(3, 5)) * 31;
        int minAmount = Integer.parseInt(intermediate.get(0).substring(0, 3));
        int maxAmount = Integer.parseInt(intermediate.get(0).substring(5, 11).replace(" ", ""));
        double creditRate = Double.parseDouble(intermediate.get(2));
        double prepayment = Double.parseDouble(intermediate.get(3));

        credit.setType(CreditType.CONSUMER);
        credit.setMinAmount(minAmount);
        credit.setMaxAmount(maxAmount);
        credit.setCurrency(Currency.UAH);
        credit.setTerm(term);
        credit.setCreditRate(creditRate);
        credit.setPrepayment(prepayment);
        credit.setName("Потребительский кредит");
        credit.setBank(new AlphaConsCreditParser().bank);
        credit.setUrl(CREDIT_URL);
        credit.setState(State.ACTIVE);
        creditParam.add(credit);
        return creditParam;
    }
}
